<template>
  <div>
    <div class="btn">
      <a-button type="primary" @click="addjobHistoryClkFn">新增工作经历</a-button>
    </div>

    <div class="table">
      <a-table rowKey="id" :columns="jobExperienceColumns" :data-source="jobExperienceData" :pagination="false">
        <template v-for="col in jobExperienceColumns" :slot="col.dataIndex" slot-scope="text, record">
          <div :key="col.dataIndex">
            <a-input v-if="
                record.editable &&
                (col.dataIndex == 'companyName' ||
                  col.dataIndex == 'postName' ||
                  col.dataIndex == 'content')
              " style="margin: -5px 0" :value="text" @change="
                (e) => handleChange(e.target.value, record.key, col.dataIndex)
              "></a-input>
            <a-date-picker style="width: 200px" @change="
                (date, dateString) =>
                  dateOnChange(dateString, record.key, col.dataIndex)
              " v-else-if="
                record.editable &&
                (col.dataIndex == 'beginDate' || col.dataIndex == 'endDate')
              " :default-value="moment(moment(text), dateFormat)" />
            <template v-else>{{ text | dateFormatFilter }}</template>
          </div>
        </template>

        <span slot="opera" slot-scope="text, record">
          <div class="editable-row-operations">
            <span v-if="record.editable">
              <a @click="() => save(record.key)">保存</a>
              <a-popconfirm title="确定取消?" @confirm="() => cancel(record.key)">
                <a>取消</a>
              </a-popconfirm>
            </span>
            <span v-else>
              <a :disabled="editingKey !== ''" @click="() => edit(record.key)">编辑</a>
              <a-divider type="vertical" />
              <a @click="() => delectClkFn(record.id)">删除</a>
            </span>
          </div>
        </span>
      </a-table>
    </div>

    <!-- 新增工作经历modal -->
    <a-modal title="新增工作经历" :visible="modalVisible" :confirm-loading="confirmLoading" @ok="handleOk" @cancel="handleCancel" centered>
      <a-form-model :model="modalForm" :label-col="labelCol" :wrapper-col="wrapperCol" ref="modalFormDom">
        <a-form-model-item label="企业名称" prop="corpName">
          <a-input v-model="modalForm.corpName" placeholder="请输入企业名称" />
        </a-form-model-item>
        <a-form-model-item label="职位" prop="position">
          <a-input v-model="modalForm.position" placeholder="请输入职位" />
        </a-form-model-item>
        <a-form-model-item label="入职时间" prop="entryDate">
          <a-date-picker @change="entryOnChange" v-model="modalForm.entryDate" placeholder="请选择入职时间" :style="resetWidth" />
        </a-form-model-item>
        <a-form-model-item label="离职时间" prop="leaveDate">
          <a-date-picker @change="leaveOnChange" v-model="modalForm.leaveDate" placeholder="请选择离职时间" :style="resetWidth" />
        </a-form-model-item>
        <a-form-model-item label="简述" class="wordStatistics_wrapper" prop="desc">
          <a-textarea :style="resetWidth" placeholder="请输入内容" :maxLength="300" :auto-size="{ minRows: 2, maxRows: 6 }" v-model="modalForm.desc" />
          <span class="wordStatistics">{{ modalForm.desc.length }}/300</span>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import datas from "@/utils/data";
import moment from "moment";
import { transferDate } from "@/utils/util";
import {
  jobHistoryAddOrUpdateApi,
  jobHistory,
  jobHistoryDelByIdApi,
} from "@/services/employeeDetail";

export default {
  name: "tabs5",
  props: {
    jobHistoryList: Array,
  },
  filters: {
    dateFormatFilter (val) {
      if (typeof val == "number") {
        return transferDate(val, 0);
      } else {
        return val;
      }
    },
  },
  watch: {
    jobHistoryList (n) {
      this.jobExperienceData = n;
    },
  },
  data () {
    this.cacheData = this.jobHistoryList.map((item) => ({ ...item }));
    return {
      jobExperienceColumns: datas.jobExperienceColumns,
      jobExperienceData: this.jobHistoryList,
      editingKey: "",
      dateFormat: "YYYY/MM/DD",
      modalVisible: false,
      confirmLoading: false,
      modalForm: {
        corpName: "",
        position: "",
        entryDate: "",
        leaveDate: "",
        desc: "",
      },
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      resetWidth: "width: 275px;",
    };
  },
  methods: {
    moment,

    getData () {
      /**
       * @description: 工作经历接口
       * @param {*}
       * @return {*}
       */

      let params = {
        userId: this.$Storage.get("employDetail_userId"),
      };
      jobHistory(params).then((res) => {
        let { code } = res.data;
        if (code == 200) {
          // this.jobHistoryList = data;
          this.$emit("updatesData");
        }
      });
    },

    entryOnChange (date, dateString) {
      console.log(date, dateString);
      this.modalForm.entryDate = dateString;
    },

    leaveOnChange (date, dateString) {
      console.log(date, dateString);
      this.modalForm.leaveDate = dateString;
    },

    handleOk () {
      // 新增工作经历
      this.confirmLoading = true;
      let { corpName, position, entryDate, leaveDate, desc } = this.modalForm;
      let params = {
        // id: undefined, // 新增无ID
        userId: this.$Storage.get("employDetail_userId"),
        beginDateStr: entryDate,
        endDateStr: leaveDate,
        companyName: corpName,
        deptName: "", // 部门
        postName: position,
        content: desc,
      };
      this.addUpdateJobHistoryPackApi(params);
    },

    addUpdateJobHistoryPackApi (params) {
      jobHistoryAddOrUpdateApi(params).then((res) => {
        this.modalVisible = false;
        this.confirmLoading = false;

        let { code, msg } = res.data;
        if (code === 200) {
          this.$message.success(msg);
          this.getData();
        } else if (code === 400) {
          this.$message.error(msg);
        }
      });
    },

    handleCancel () {
      this.modalVisible = false;
    },

    addjobHistoryClkFn () {
      this.modalVisible = true;
      this.$nextTick(() => {
        this.$refs["modalFormDom"].resetFields();
      });
    },

    dateOnChange (dateString, key, column) {
      const newData = [...this.jobExperienceData];
      const target = newData.filter((item) => key === item.key)[0];
      if (target) {
        target[column] = dateString;
        this.jobExperienceData = newData;
      }
    },
    handleChange (value, key, column) {
      const newData = [...this.jobExperienceData];
      const target = newData.filter((item) => key === item.key)[0];
      if (target) {
        target[column] = value;
        this.jobExperienceData = newData;
      }
    },
    edit (key) {
      const newData = [...this.jobExperienceData];
      const target = newData.filter((item) => key === item.key)[0];
      this.editingKey = key;
      if (target) {
        target.editable = true;
        this.jobExperienceData = newData;
      }
    },
    save (key) {
      const newData = [...this.jobExperienceData];
      const newCacheData = [...this.cacheData];
      const target = newData.filter((item) => key === item.key)[0];
      const targetCache = newCacheData.filter((item) => key === item.key)[0];
      if (target && targetCache) {
        delete target.editable;
        this.jobExperienceData = newData;
        Object.assign(targetCache, target);
        this.cacheData = newCacheData;
      }
      this.editingKey = "";

      // 编辑
      let { id, companyName, postName, beginDate, endDate, content } = target;
      let params = {
        id,
        userId: this.$Storage.get("employDetail_userId"),
        beginDateStr: beginDate,
        endDateStr: endDate,
        companyName,
        postName,
        content,
      };
      this.addUpdateJobHistoryPackApi(params);
    },
    cancel (key) {
      const newData = [...this.jobExperienceData];
      const target = newData.filter((item) => key === item.key)[0];
      this.editingKey = "";
      if (target) {
        Object.assign(
          target,
          this.cacheData.filter((item) => key === item.key)[0]
        );
        delete target.editable;
        this.jobExperienceData = newData;
      }
    },

    delectClkFn (data) {
      let params = {
        id: data,
      };

      jobHistoryDelByIdApi(params).then((res) => {
        let { code, msg } = res.data;

        if (code === 200) {
          this.$message.success(msg);
          this.$emit("updatesData");
        } else if (code === 400) {
          this.$message.error(msg);
        }
      });
    },
  },
};
</script>

<style scoped lang="less">
.btn {
  margin: 0 0 20px;
  display: none;
}

.editable-row-operations a {
  margin-right: 8px;
}

.wordStatistics_wrapper {
  position: relative;
  .wordStatistics {
    position: absolute;
    bottom: -30px;
    right: 0;
    line-height: 1;
  }
}
</style>